package com.xhs.zdl.demo.expandableListView;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import com.xhs.zdl.demo.R;

import java.util.List;
import java.util.Map;

/**
 * Created by zdl on 2017/10/18.
 * email zdl328465042@163.com
 */

public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<String> parent;
    private Map<String, List<String>> child;
    private LayoutInflater inflater;

    public ExpandableListViewAdapter(Context context, List<String> parent, Map<String, List<String>> child) {
        this.context = context;
        this.parent = parent;
        this.child = child;
        inflater = LayoutInflater.from(context);
    }

    //parent的count
    @Override
    public int getGroupCount() {
        return parent.size();
    }

    //child的count
    @Override
    public int getChildrenCount(int i) {
        String key = parent.get(i);
        return child.get(key).size();
    }

    //parent
    @Override
    public Object getGroup(int i) {
        return parent.get(i);
    }

    //child
    @Override
    public Object getChild(int i, int i1) {
        String key = parent.get(i);
        return child.get(key).get(i1);
    }

    //parent的position
    @Override
    public long getGroupId(int i) {
        return i;
    }

    //child的position
    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    //设置parent组件
    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        ParentViewHolder holder;
        if (null == view){
            holder = new ParentViewHolder();
            view = inflater.inflate(R.layout.expandable_parent_layout, null);
            holder.tv = view.findViewById(R.id.expandable_parent_tv);

            view.setTag(holder);
        }else
            holder = (ParentViewHolder) view.getTag();

        holder.tv.setText(parent.get(i));

        return view;
    }

    //设置child的组件
    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        ChildViewHolder holder;
        if (null == view){
            holder = new ChildViewHolder();
            view = inflater.inflate(R.layout.exandable_child_layout, null);
            holder.tv = view.findViewById(R.id.expandable_child_tv);

            view.setTag(holder);
        }else
            holder = (ChildViewHolder) view.getTag();

        String key = parent.get(i);
        holder.tv.setText(child.get(key).get(i1));

        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    class ParentViewHolder{
        TextView tv;
    }

    class ChildViewHolder{
        TextView tv;
    }
}
